package com.tvunetworks.center.user.config.memcache;

import net.spy.memcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;

/**
 *
 * 示例紧用作示例
 *
 * @author lebron
 * @ClassName: MemcacheClientServer
 *  2018年4月11日
 */
@Configuration
public class MemcaheClientConfiguration {

    private static final String LOCALHOST = "localhost";
    private static final int DEFAULT_PORT = 11211;

    public MemcaheClientConfiguration() {
    }

    @Autowired
    private Environment environment;

    /**
     *
     * @return MemcachedClient
     * @throws IOException 编译异常
     */
    @Bean(name = "ccMemcacheClient")
    public MemcachedClient ccMemcacheClient() throws IOException {
        String servers = this.environment.getProperty("ccMemcacheServer");
        return configMemcachedClient(servers);
    }

    /**
     *
     * @return MemcachedClient
     * @throws IOException 编译异常
     */
    @Bean(name = "tpdsMemcacheClient")
    public MemcachedClient tpdsMemcacheClient() throws IOException {
        String servers = this.environment.getProperty("tpdsMemcacheServer");
        return configMemcachedClient(servers);
    }

    private MemcachedClient configMemcachedClient(String servers) throws IOException {
        ArrayList<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>();
        if (StringUtils.isEmpty(servers)) {
            addresses.add(new InetSocketAddress(LOCALHOST, DEFAULT_PORT));
        } else {
            String[] serverArray = servers.split(",");
            int length = serverArray.length;
            for (int i = 0; i < length; ++i) {
                String server = serverArray[i];
                int colon = server.indexOf(":");
                if (colon == -1) {
                    addresses.add(new InetSocketAddress(server, 11211));
                } else {
                    int port = Integer.parseInt(server.substring(colon + 1));
                    addresses.add(new InetSocketAddress(server.substring(0, colon), port));
                }
            }
        }
        return new MemcachedClient(addresses);
    }
}
